<script setup lang="ts">
import { message } from '@/components/XtxUI';
import { useCountDown } from '@/hooks';
import router from '@/router';
import { useMemberStore } from '@/store';
import type { QQUserInfo } from '@/types';
import { codeRule, mobileRule } from '@/utils/validate';
import { useField, useForm } from 'vee-validate';

// 获取 unionId 用于绑定登录，获取 userInfo 用于界面渲染
const { unionId, userInfo } = defineProps<{
  userInfo: QQUserInfo | undefined;
  unionId: string;
}>();

// 表单信息收集
// const form = reactive({
//   mobile: '13012345729',
//   code: '123456',
// });
// 表单验证
const { validate, resetForm } = useForm({
  validationSchema: {
    mobile: mobileRule,
    code: codeRule,
  },
})
const { value: mobile, errorMessage: mobileError } = useField<string>('mobile')
const { value: code, errorMessage: codeError } = useField<string>('code')
// 获取会员 Store
const member = useMemberStore();
// member.sendCodeBind(mobile)
const { count, start } = useCountDown()
const send = () => {
  if (count.value > 0) return
  member.sendCodeBind(mobile.value)
  message({ type: 'success', text: '发送验证码成功' })
  start(60)
}
// 点击绑定按钮(绑定登录)
const loginBtn = async () => {
  const res = await validate()
  if (!res.valid) return
  // ...省略表单校验
  // console.log(unionId, form);
  // 调用绑定登录接口
  await member.loginBind({
    mobile: mobile.value,
    code: code.value, // 表单数据
    unionId, // 三方标识
  });

  message({ type: 'success', text: 'QQ绑定成功' })
  router.push('/')
};
</script>

<template>
  <div class="xtx-form">
    <div class="user-info">
      <img :src="userInfo?.data.figureurl_qq_2" alt="" />
      <p>
        Hi，{{ userInfo?.data.nickname }}
        欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~
      </p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <input v-model="mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error" v-if="mobileError">{{ mobileError }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <input v-model.trim="code" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="send">
          {{
          count === 0 ? '发送验证码' : `${count}s后发送`
          }}
        </span>
      </div>
      <div class="error" v-if="codeError">{{ codeError }}</div>
    </div>
    <a @click="loginBtn" href="javascript:;" class="submit">立即绑定</a>
  </div>
</template>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;

  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }

  p {
    padding-left: 10px;
  }
}

.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;

  &:hover {
    cursor: pointer;
  }
}
</style>
